# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################

# coding: utf8

def index():
    if auth.is_logged_in():
        if db(db.auth_group.role=='admin').count() > 0:
            roleId = db(db.auth_group.role=='admin').select()[0]
            if db((db.auth_membership.user_id==auth.user.id)&(db.auth_membership.group_id==roleId)).count()>0:
                response.isAdmin = True
    return dict()

@auth.requires_login()
def setup():
    if db(db.auth_group.role=='admin').count() == 0:
        if 'admin_email' in request.post_vars:
            adminId = db.auth_group.insert(role='admin')
            uploaderId = db.auth_group.insert(role='uploader')
            db.auth_membership.insert(user_id=auth.user.id,group_id=adminId)
            db.auth_membership.insert(user_id=auth.user.id,group_id=uploaderId)
        else:
            response.setup = True
    return dict()

@auth.requires_membership('admin')
def uploaders():
    roleId = db(db.auth_group.role=='uploader').select()[0].id
    if 'toggle' in request.get_vars:
        query = (db.auth_membership.user_id==request.get_vars['toggle'])&(db.auth_membership.group_id==roleId)
        if db(query).count() > 0:
            db(query).delete()
        else:
            db.auth_membership.insert(group_id=roleId,user_id=request.get_vars['toggle'])
        redirect(URL(r=request, c='default',f='uploaders'))
    users = db(db.auth_user.id>0).select()
    rows = db(db.auth_membership.group_id==roleId).select()
    uploaders = []
    for r in rows:
        uploaders.append(r.user_id)
    return dict(users=users,uploaders=uploaders)

@auth.requires_membership('uploader') 
def upload():
    form=SQLFORM(db.file, fields=['file'])
    if '_formname' in request.post_vars:
        db.file.filename.default = request.vars.file.filename
        db.file.user_id.default = auth.user.id
    if form.accepts(request.vars): 
        response.flash='File uploaded'
    return dict(form=form)

@auth.requires(auth.requires_membership('uploader') or auth.requires_membership('downloader'))
def files():
    if 'del' in request.get_vars:
        db((db.file.user_id==auth.user.id)&(db.file.id==request.get_vars['del'])).delete()
        redirect(URL(r=request,c='default',f='files'))
    elif 'ren' in request.get_vars and request.get_vars['new'] != 'null':
        file = db((db.file.user_id==auth.user.id)&(db.file.id==request.get_vars['ren'])).select()[0]
        if request.get_vars['new'].find('.') == -1:
            filename = request.get_vars['new'] + '.' + file.filename.split('.').pop()
        else:
            filename = request.get_vars['new']
        db(db.file.id==file.id).update(filename=filename)
        redirect(URL(r=request,c='default',f='files'))
    files=db(db.file.id>0).select(orderby=db.file.filename)
    return dict(files=files)
 
@auth.requires_membership('downloader')
def downloader():
    if 'del' in request.get_vars:
        db((db.file.user_id==auth.user.id)&(db.file.id==request.get_vars['del'])).delete()
        redirect(URL(r=request,c='default',f='files'))
    elif 'ren' in request.get_vars and request.get_vars['new'] != 'null':
        file = db((db.file.user_id==auth.user.id)&(db.file.id==request.get_vars['ren'])).select()[0]
        if request.get_vars['new'].find('.') == -1:
            filename = request.get_vars['new'] + '.' + file.filename.split('.').pop()
        else:
            filename = request.get_vars['new']
        db(db.file.id==file.id).update(filename=filename)
        redirect(URL(r=request,c='default',f='files'))
    files=db(db.file.id>0).select(orderby=db.file.filename)
    return dict(files=files)

    
def file():
    file = db(db.file.filename==request.args[0]).select()
    if len(file) > 0:
        request.args[0] = file[0].file
        return response.download(request,db)
    else:
        return


def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()


@auth.requires_signature()
def data():
    """
    http://..../[app]/default/data/tables
    http://..../[app]/default/data/create/[table]
    http://..../[app]/default/data/read/[table]/[id]
    http://..../[app]/default/data/update/[table]/[id]
    http://..../[app]/default/data/delete/[table]/[id]
    http://..../[app]/default/data/select/[table]
    http://..../[app]/default/data/search/[table]
    but URLs bust be signed, i.e. linked with
      A('table',_href=URL('data/tables',user_signature=True))
    or with the signed load operator
      LOAD('default','data.load',args='tables',ajax=True,user_signature=True)
    """
    return dict(form=crud())
